package com.education.interceptor;

import com.education.annotation.AuthorityAnnotation;
import com.education.common.Const;
import com.education.pojo.Admin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author 林心晨
 * @Title:
 * @Package
 * @Description:
 * @date create in 5.4  9:07
 */
public class PermissionInterceptor implements HandlerInterceptor{

    private Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(handler.getClass().getName());   // 处理方法全路径
        System.out.println(request.getRequestURI());        // /test
        System.out.println(request.getRequestURL());        // http://8080
        HttpSession session = request.getSession();
        if (handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            Class<?> clazz=hm.getBeanType();
            Method m=hm.getMethod();
            if (clazz != null && m != null){
                boolean isClzAnnotation= clazz.isAnnotationPresent(AuthorityAnnotation.class);
                boolean isMethondAnnotation=m.isAnnotationPresent(AuthorityAnnotation.class);
                AuthorityAnnotation auth = null;
                if(isMethondAnnotation){
                    auth=m.getAnnotation(AuthorityAnnotation.class);
                }else if(isClzAnnotation){
                    auth=clazz.getAnnotation(AuthorityAnnotation.class);
                }
                if (auth == null){
                    return false ;
                }
                int authority = auth.authority();
                Admin admin = (Admin) session.getAttribute(Const.CURRENT_Admin);
                if (admin == null){
                    return false ;
                }
                if (!(admin.getRoleId() == authority)){
                    response.setStatus(401);
                    return false ;  //整个请求结束
                }
            }
        }
        return true ;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
